package com.abo.yaas.webservice;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;

import com.abo.yaas.domain.Bid;
import com.abo.yaas.webservice.constants.Operation;
import com.abo.yaas.webservice.constants.URLConstants;
import com.abo.yaas.webservice.exceptions.InvalidCredentialsException;
import com.abo.yaas.webservice.exceptions.WebServiceException;
import com.abo.yaas.webservice.hibernate.SortCriteria;
import com.abo.yaas.webservice.hibernate.WSFilter;
import com.abo.yaas.webservice.utils.AuthenticationUtil;
import com.abo.yaas.webservice.utils.BidFacade;
import com.sun.jersey.core.util.MultivaluedMapImpl;
import com.sun.jersey.spi.resource.Singleton;

@Singleton
@Path(URLConstants.bidProvider)
public class BidResource extends EntityResource<Bid> {
    public BidResource() {
        super(Bid.class);
    }

    @Override
    protected WSFilter<Bid> extractFilter(UriInfo ui) {
        final WSFilter<Bid> filter = new WSFilter<Bid>();
        final MultivaluedMapImpl params = (MultivaluedMapImpl) ui.getQueryParameters();
        final Long auctionId = params.getFirst("auctionId", Long.class);
        if (auctionId != null) {
            filter.addChild(new WSFilter<Bid>("auctionId", auctionId, Operation.EQ, Bid.class));
        }
        return filter;
    }

    @Override
    protected List<SortCriteria<Bid>> extractSortCriteria(UriInfo ui) {
        final List<SortCriteria<Bid>> result = new ArrayList<SortCriteria<Bid>>();
        result.add(new SortCriteria<Bid>("id", false, Bid.class));
        return result;
    }

    @POST
    @Override
    @Produces(MediaType.APPLICATION_XML)
    @Consumes(MediaType.APPLICATION_XML)
    public Bid saveOrUpdateEntity(Bid bid, @Context HttpHeaders headers) throws WebServiceException, InvalidCredentialsException {
        AuthenticationUtil.authenticate(getUser(headers), getPassword(headers));
        return BidFacade.doPlaceBid(bid);
    }
}
